package com.qingfeng.client.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qingfeng.client.DO.ShoppingCartStoreDo;
import com.qingfeng.client.bean.Buyer;
import com.qingfeng.client.bean.ShoppingCart;
import com.qingfeng.client.service.ShoppingCartService;
import com.qingfeng.client.util.Page;
import com.qingfeng.exception.LsException;
import com.qingfeng.mjwt.LoginToken;
import com.qingfeng.util.ApiMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/1/6 2:03 下午
 */
@Api(tags = "购物车相关操作")
@RestController
@RequestMapping("/app/shoppingCartApi")
public class ShoppingCartApi extends BaseV1Api{

    @Autowired
    private ShoppingCartService shoppingCartService;


    @ApiOperation("添加购物车")
    @PostMapping("/add")
    public ApiMsg add(@RequestBody ShoppingCart shoppingCart){
        Buyer buyer = getUser();
        if (buyer!=null){
            shoppingCart.setBuyerId(buyer.getId());
            shoppingCart.setCreateTime(System.currentTimeMillis()/1000);
            shoppingCartService.add(shoppingCart);
        }
        return success();
    }

    @ApiOperation("删除购物车,购物车id 传以，分割的字符串")
    @PostMapping("/delete")
    public ApiMsg deletes(@RequestParam String ids){
        Buyer buyer = getUser();
        if (buyer!=null){
            shoppingCartService.delete(ids,buyer.getId());
        }
        return success();
    }

    @ApiOperation("更新购物车购物车，用于添加数量")
    @PostMapping("/updateNum")
    public ApiMsg updateNum(@RequestBody ShoppingCart shoppingCart) throws LsException {
        Buyer buyer = getUser();
        if (buyer!=null){
            shoppingCartService.addNum(shoppingCart.getNum(),shoppingCart.getId());
            return success();
        }else {
            return error("用户未登录");
        }
    }

    @LoginToken
    @ApiOperation("获取购物车")
    @PostMapping("/mycart")
    public ApiMsg<List<ShoppingCartStoreDo>> mycart(@RequestBody Page page){
        Buyer buyer = getUserByToken();
        if (buyer!=null){
            IPage<ShoppingCartStoreDo> page1 = shoppingCartService.getByBuyerId(page,buyer.getId());
            return successPage(page);
        }else {
            return error("用户未登录");
        }
    }
}
